package com.guli.mall.pms.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.guli.common.utils.QuickSort;
import com.guli.mall.pms.entity.SkuInfoEntity;
import com.guli.mall.pms.entity.vo.SkuInfoWithSaleEntitiesVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guli.common.utils.PageUtils;
import com.guli.common.utils.Query;

import com.guli.mall.pms.mapper.SkuSaleAttrValueMapper;
import com.guli.mall.pms.entity.SkuSaleAttrValueEntity;
import com.guli.mall.pms.service.SkuSaleAttrValueService;
import org.springframework.util.ObjectUtils;


@Service("skuSaleAttrValueService")
public class SkuSaleAttrValueServiceImpl extends ServiceImpl<SkuSaleAttrValueMapper, SkuSaleAttrValueEntity> implements SkuSaleAttrValueService {

    @Override
    public PageUtils queryPage(Integer currentPage, Integer size) {

        Page<SkuSaleAttrValueEntity> page = new Page<>(currentPage, size);

        Page<SkuSaleAttrValueEntity> resultPage = this.page(page);


        return new PageUtils(resultPage);
    }

    @Override
    public List<SkuSaleAttrValueEntity> getSaleAttrsBySkuId(Long skuId) {

        QueryWrapper<SkuSaleAttrValueEntity> wrapper = new QueryWrapper<>();

        wrapper.eq("sku_id", skuId);

        List<SkuSaleAttrValueEntity> list = this.list(wrapper);

        QuickSort.sort(list, (c1, c2) -> {
            if (!ObjectUtils.isEmpty(c1.getAttrSort()) && !ObjectUtils.isEmpty(c2.getAttrSort())) {
                return c1.getAttrSort() - c2.getAttrSort();
            }
            return 0;

        });

        return list;
    }

    @Override
    public List<SkuInfoWithSaleEntitiesVo> appendSkuSaleAttrsToEachSkuInfo(List<SkuInfoEntity> skuInfoEntities) {

        return skuInfoEntities.stream().map(otherSkuInfo -> {
            Long otherSkuInfoId = otherSkuInfo.getSkuId();

            List<SkuSaleAttrValueEntity> otherSkuInfoSaleAttrs = this.getSaleAttrsBySkuId(otherSkuInfoId);

            SkuInfoWithSaleEntitiesVo otherSkuInfoWithSaleEntities = new SkuInfoWithSaleEntitiesVo();

            BeanUtils.copyProperties(otherSkuInfo, otherSkuInfoWithSaleEntities);

            otherSkuInfoWithSaleEntities.setSaleAttrList(otherSkuInfoSaleAttrs);

            return otherSkuInfoWithSaleEntities;
        }).collect(Collectors.toList());
    }

}